import os

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import platform
import time
import threading
from controllers.Base import *
from controllers import *
from controllers.XcmsController import XcmsStreamAddProxyController, XcmsStreamDelProxyController, \
    XcmsStreamPtzController
from settings import g_settings,g_logger,PROJECT_NAME

def xcnvs_admin(ip, port, debug=True):
    g_logger.info("xcnvs_admin() ws://%s:%d" % (ip, port))
    g_logger.info("xcnvs_admin() http://%s:%d" % (ip, port))
    g_logger.info(g_settings.getStr())

    def __cleanupThread():
        while True:
            try:
                __cur_timestamp = int(time.time())

                # 删除
                __k_array = []
                for k,v in g_messageCmdXcmsStreamList.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp
                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsStreamList[k]

                # 删除
                __k_array = []
                for k,v in g_messageCmdXcmsLiveStart.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsLiveStart[k]


                # 删除
                __k_array = []
                for k,v in g_messageCmdXcmsLiveStop.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsLiveStop[k]


                # 删除
                __k_array = []
                for k,v in g_messageCmdXcmsRecordTimeline.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsRecordTimeline[k]

                # 删除
                __k_array = []
                for k,v in g_messageCmdXcmsRecordFilename.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsRecordFilename[k]

                # 删除(2025/1/5新增)
                __k_array = []
                for k,v in g_messageCmdXcmsStreamAddProxy.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsStreamAddProxy[k]

                # 删除(2025/1/5新增)
                __k_array = []
                for k,v in g_messageCmdXcmsStreamDelProxy.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsStreamDelProxy[k]

              # 删除(2025/1/5新增)
                __k_array = []
                for k,v in g_messageCmdXcmsStreamPtz.items():
                    message_timestamp = v["message_timestamp"]
                    alive_duration = __cur_timestamp - message_timestamp

                    if alive_duration > g_settings.adminCacheDuration:
                        __k_array.append(k)

                for k in __k_array:
                    del g_messageCmdXcmsStreamPtz[k]

            except Exception as e:
                g_logger.error("__cleanupThread() e:%s"%str(e))
            time.sleep(g_settings.adminCacheCheckInterval)

    t = threading.Thread(target=__cleanupThread)
    t.daemon = True
    t.start()

    # tornado.options.parse_command_line()
    max_buffer_size = 1024 * 1024 * 10  # 文件最大上传字节长度（10M）
    if "Windows" == platform.system() or "windows" == platform.system():
        reuse_port = False  # Windows平台不支持端口复用
        autoreload = False
        num_processes = 1
    else:
        reuse_port = True
        autoreload = False
        num_processes = 1

    routes = [
            (r"/", WebIndexController),
            (r"/websocket", WsController),
            (r"/xcms/list", XcmsListController),
            (r"/xcms/stream/list", XcmsStreamListController),
            (r"/xcms/stream/add/proxy", XcmsStreamAddProxyController),
            (r"/xcms/stream/del/proxy", XcmsStreamDelProxyController),
            (r"/xcms/stream/ptz", XcmsStreamPtzController),
            (r"/xcms/live/start", XcmsLiveStartController),
            (r"/xcms/live/stop", XcmsLiveStopController),
            (r"/xcms/record/timeline", XcmsRecordTimelineController),
            (r"/xcms/record/filename", XcmsRecordFilenameController),
            (r"/xcnvs/message", XcnvsMessageController),
            (r"/xcnvs/close/stream", XcnvsCloseStreamsController)
        ]

    if g_settings.dev:
        routes.append((r"/xcnvs/dev/cache", XcnvsDevCacheController))
        routes.append((r"/xcnvs/dev/media/list", XcnvsDevMediaListController))

    app = tornado.web.Application(routes,
        websocket_ping_interval=5, # WebSocket ping探活包发送间隔秒数
        xsrf_cookies=False,
        cookie_secret=PROJECT_NAME,
        autoreload=autoreload, #
        debug=debug,
        template_path="templates",
        static_path="static",
        )

    server = tornado.httpserver.HTTPServer(app, max_buffer_size=max_buffer_size)
    server.bind(port=port, reuse_port=reuse_port)
    server.start(num_processes=num_processes)
    tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
    xcnvs_admin(g_settings.ip, g_settings.adminPort, debug=g_settings.debug)
